﻿using System;
using ALC.Core.Constants;
using ALC.Core.Enums;
using PLCCommunication.Core;
using PLCCommunication.Core.Interfaces;

namespace ALC.Core.Misc
{
    public class PlcCommandParser : ICustomCommandParser
    {

        #region constant

        private const int CommandId_BalancingStart = 102;

        private const int CommandId_ThicknessMeasureStart = 103;
        private const int CommandId_WorkpieceEnter = 104;
        private const int CommandId_ScanCode1 = 999999;
        
        private const int Para1_FirstTimeAdjust = 0;

        #endregion

        #region event

        public event Action<bool> PlcAskForAngles;
        public event Action<int> ThicknessMeasureStart;
        public event Action<CavityType> WorkpieceEnter;

        public event Action ScanCode1;

        #endregion
        
        public void ParseCustomCommand(PlcMessagePack messagePack)
        {
            switch (messagePack.CommandId)
            {
                case CommandId_BalancingStart:
                    var isFirstTimeCurrentWorkpiece = Convert.ToInt32(messagePack.Param1) == Para1_FirstTimeAdjust;
                    OnPlcAskForAngles(isFirstTimeCurrentWorkpiece);
                    break;
                case CommandId_ThicknessMeasureStart:
                    OnThicknessMeasureStart(Convert.ToInt32(messagePack.Param1));
                    break;
                case CommandId_WorkpieceEnter:
                    var cavityNo = Convert.ToInt32(messagePack.Param1);
                    var enterCavity = (CavityType) cavityNo;
                    OnWorkpieceEnter(enterCavity);
                    break;
                case CommandId_ScanCode1:
                    OnScanCode1();
                    break;
            }
        }

        protected virtual void OnPlcAskForAngles(bool isFirstTimeCurrentWorkpiece)
        {
            PlcAskForAngles?.Invoke(isFirstTimeCurrentWorkpiece);
        }

        protected virtual void OnThicknessMeasureStart(int positionIndex)
        {
            ThicknessMeasureStart?.Invoke(positionIndex);
        }

        protected virtual void OnWorkpieceEnter(CavityType obj)
        {
            WorkpieceEnter?.Invoke(obj);
        }

        protected virtual void OnScanCode1()
        {
            ScanCode1?.Invoke();
        }
    }
}